package com.etrans.web.gps.business.alarm.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.alarm.domain.AlarmDealInfo;
import com.etrans.web.gps.business.alarm.domain.AlarmGroupStatistics;
import com.etrans.web.gps.business.alarm.domain.AlarmHistoryInfo;
import com.etrans.web.gps.business.alarm.domain.AlarmHourStatistics;
import com.etrans.web.gps.business.alarm.domain.AlarmPenddingInfo;
import com.etrans.web.gps.business.alarm.service.AlarmService;
import com.etrans.web.gps.business.gis.service.MonitorService;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.AlarmKindUtil;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
import com.etrans.web.gps.util.grid.ParamMap;

/**
 * <p>
 * Title: AlarmController.java<／p>
 * <p>
 * Description:实时报警处理controller <／p>
 * <p>
 * Copyright: Copyright (c) 2007<／p>
 * <p>
 * Company: E-trans<／p>
 *
 * @author lxd
 * @version 1.0
 * @date 2017年6月17日
 * @time 下午2:58:33
 */
@Controller
@RequestMapping("/alarm")
@SuppressWarnings("unchecked")
public class AlarmController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(AlarmController.class);

	@Autowired
	private AlarmService alarmService;

	
	@Autowired
	private MonitorService monitorService;

	@Autowired
	private AlarmKindUtil alarmKindUtil;

	private static Map<Integer, String> staticAlarmMap = new ConcurrentHashMap<Integer, String>();

	/**
	 * 报警的业务时间
	 **/
	private static long ALARM_BUSINESS_TIME = 3 * 60 * 60 * 1000;

	@RequestMapping(value = "/history.html", method = RequestMethod.GET)
	public ModelAndView toHistory() {
		ModelAndView modelAndView = new ModelAndView();
		SysUser user = this.getSysUser();
		modelAndView.addObject("username", user.getLogin_name());
		modelAndView.setViewName("views/business/alarm/historyAlarm");
		return modelAndView;
	}


	/**
	 *@author yhq
	 *@description  导出历史报警数据
	 *@methodName
	 *@retutn
	 *@date 2017/8/10 10:40
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "exportHistory.html")
	public void exportHistory( HttpServletRequest request, HttpServletResponse response, String paramsGrid, String colModel, String title, String StartPage, String EndPage, String pagesize) {
		Map<String, Object> paramMap=getReqParameters();
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		SysUser user = getSysUser();
		List<String> whereParamsList = JSON.parseObject(paramMap.get("queryParams").toString(), List.class);
		HashMap<String, Object> param = new HashMap<String, Object>();
		for (Object object : whereParamsList) {
			JSONObject jsonObject = (JSONObject) object;
			param.put(jsonObject.get("name").toString(),jsonObject.get("value"));
		}
		param.put("userId", user.getId());
		paramMap.putAll(param);

		PageVo pageVo = alarmService.getHistoryAlarm(paramMap);
		List<AlarmHistoryInfo> list = (List<AlarmHistoryInfo>)pageVo.getRows();
		List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		int start=Integer.valueOf(Integer.valueOf(StartPage)-1)*Integer.valueOf(pagesize);
		int end=Integer.valueOf(EndPage)*Integer.valueOf(pagesize);
		if(end>(list.size()-1)){
			end=list.size();
		}
		for(int i=start;i<end;i++){
			HashMap<String, Object> map = new HashMap<String, Object>();

			AlarmHistoryInfo obj=(AlarmHistoryInfo)list.get(i);
			map.put("registrationNO", obj.getRegistrationNO()==null ? "" : obj.getRegistrationNO());
			map.put("internalNo", obj.getInternalNo()==null ? "" : obj.getInternalNo());
			map.put("vehicleTeamName", obj.getVehicleTeamName()==null ? "" : obj.getVehicleTeamName());
			map.put("alarmSource", obj.getAlarmSource()==null ? "" : obj.getAlarmSource());
			map.put("alarmParam", obj.getAlarmParam()==null ? "" : obj.getAlarmParam());
			map.put("alarmTime", obj.getAlarmTime()==null ? "" : obj.getAlarmTime());
			map.put("dealTime", obj.getDealTime()==null ? "" : obj.getDealTime());
			map.put("dealContent", obj.getDealContent()==null ? "" : obj.getDealContent());
			map.put("dealer", obj.getDealer()==null ? "" : obj.getDealer());
			map.put("alarmkind", String.valueOf(obj.getAlarmkind())==null ? "" : staticAlarmMap.get(obj.getAlarmkind()));
			rows.add(map);
		}
		int index=-1;
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response,title, removeHeadName(colModelList,index,-1),rowsList,null);
	}

//	/**
//	 * 跳转实时报警页面 实现逻辑 1. 查询该用户下的车辆静态数据，前端缓存在js中 2. 实时报警通过redis的数据跟 缓存中的静态数据拼装数据显示
//	 */
//	@RequestMapping(value = "/realtime/info.html", method = RequestMethod.GET)
//	public ModelAndView alarmInfo() {
//		ModelAndView modelAndView = new ModelAndView();
//		SysUser user = this.getSysUser();
//		Integer userId = user.getId();
//		HashMap<String, Object> param = new HashMap<String, Object>();
//		param.put("userId", userId);
//		// 查询静态数据
//		List<HashMap<String, String>> vehList = this.alarmService.getVehStaticInfo(param);
//		modelAndView.addObject("vehList", JSON.toJSONString(vehList));
//		/**
//		 * 组装数据实时分组数据
//		 */
//		HashMap<String, String> item = null;
//		String[] commnos = new String[vehList.size()];
//		for (int i = 0; i < vehList.size(); i++) {
//			item = vehList.get(i);
//			commnos[i] = item.get("CommNO");
//		}
//		Set<Integer> alarmKindIds = alarmKindUtil.getAlarmKind();
//		//右侧分组统计数据
//		List<AlarmGroupStatistics> list = getAlarmGroupStatisticsList(alarmKindIds,commnos);
//		//左侧待处理报警数据,前端js缓存，利用表格插件静态插入数据
//		PageVo pageVo = getAlarmPendingInfo(0,commnos,alarmKindIds,1,100);
//		
//		modelAndView.addObject("alarmGroup", list);
//		modelAndView.addObject("pendingList", JSON.toJSONString(pageVo));
//		
//		
//		modelAndView.addObject("username", user.getLogin_name());
//		modelAndView.setViewName("views/business/alarm/realAlarm");
//
//		return modelAndView;
//	}
	
//	/**
//	 * 获取实时分组数据
//	 * @param param
//	 * @return
//	 */
//	public List<AlarmGroupStatistics> getAlarmGroupStatisticsList(Set<Integer> alarmKindIds,String[] commnos){
//		List<TIntfObjAlarmT> tIntfObjAlarmTList = this.monitorService.getAlarmT(alarmKindIds, commnos);
//		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
//		long curr = System.currentTimeMillis();
//		int alarmType = 0;
//		for (TIntfObjAlarmT objAlarm : tIntfObjAlarmTList) {
//			if (curr - objAlarm.getAlarmTime() <= ALARM_BUSINESS_TIME) {
//				alarmType = objAlarm.getAlarmType();
//				if (map.containsKey(alarmType)) {
//					map.put(alarmType, map.get(alarmType) + 1);
//				} else {
//					map.put(alarmType, 1);
//				}
//				
//			}
//		}
//		Set<Integer> alarmTypes = map.keySet();
//		List<AlarmGroupStatistics> list = new ArrayList<AlarmGroupStatistics>();
//		AlarmGroupStatistics alarmGroupStatistics = null;
//		for (Integer key : alarmTypes) {
//			alarmGroupStatistics = new AlarmGroupStatistics();
//			alarmGroupStatistics.setAlarmType(key);
//			alarmGroupStatistics.setCount(map.get(key));
//			alarmGroupStatistics.setAlarmName(staticAlarmMap.get(key));
//			list.add(alarmGroupStatistics);
//		}
//		return list;
//	}
	
//	public PageVo getAlarmPendingInfo(int alarmType,String[] commnos,Set<Integer> alarmKindIds,int page,int pageSize) {
//		List<TIntfObjAlarmT> AlarmList = new ArrayList<>();
//		List<TIntfObjAlarmT> alarmTempList = new ArrayList<>();
//		PageVo vo = new PageVo();
//
//		alarmTempList = monitorService.getAlarmT(alarmKindIds, commnos);
//		if (alarmType != 0) {
//			for (TIntfObjAlarmT obj : alarmTempList) {
//				if (alarmType == obj.getAlarmType()) {
//					AlarmList.add(obj);
//				}
//			}
//		} else {
//			AlarmList.addAll(alarmTempList);
//		}
//
//		List<AlarmPenddingInfo> list = new ArrayList<>();
//		long curr = System.currentTimeMillis();
//		AlarmPenddingInfo entity = null;
//		for (TIntfObjAlarmT obj : AlarmList) {
//			if (curr - obj.getAlarmTime() <= ALARM_BUSINESS_TIME) {
//				entity = new AlarmPenddingInfo();
//				entity.setAlarmTypeId(String.valueOf(obj.getAlarmType()));
//				entity.setAlarmType(staticAlarmMap.get(obj.getAlarmType()));
//				entity.setCommNo(obj.getCommNo());
//				entity.setAlarmInfo(obj.getAlmParams());
//				entity.setAlarmTime(DateUtil.getDateFromLong(obj.getAlarmTime(), " yyyy-MM-dd HH:mm:ss"));
//				entity.setTime(obj.getAlarmTime());
//				if (obj.getSourceID() == 1) {
//					entity.setAlarmSource("终端报警");
//				} else {
//					entity.setAlarmSource("平台报警");
//				}
//				list.add(entity);
//			}
//			
//		}
//		int fromNo = (page - 1) * pageSize;
//		int limit = page * pageSize;
//		
//		Collections.sort(list);
//		List<AlarmPenddingInfo> result = new ArrayList<>();
//		int size = list.size();
//		for(int j = fromNo ; j < limit ; j++){
//			if(j < size ){
//				entity = list.get(j);
//				entity.setRowId(j+1);
//				result.add(entity);
//			}else{
//				break;
//			}
//		}
//		vo.setRows(result);
//		vo.setTotal(list.size());
//		vo.setPage(page);
//
//		return vo;
//	}

	/**
	 * 查询右侧实时报警分组统计数据
	 */
//	@ResponseBody
//	@RequestMapping(value = "/realtime/group.html", method = RequestMethod.POST)
//	public Map<String, Object> getRealTimeAlarmGroup(HttpServletRequest request, String CommNOs,
//			int alarmType,int page,int pageSize,String selectCommNO,int tabIndex) {
//		Map<String, Object> result = new HashMap<String, Object>();
//		try {
//			result.put("data", "0");
//			String[] commnos = CommNOs.split(",");
//			Set<Integer> alarmKindIds = alarmKindUtil.getAlarmKind();
//			//int i = 1 / 0;
//			// 加载右侧实时报警分组数据
//			List<AlarmGroupStatistics> list = getAlarmGroupStatisticsList(alarmKindIds,commnos);
//			
//			//左侧待处理报警数据,前端js缓存，利用表格插件静态插入数据
//			PageVo pageVo = null;
//			if(tabIndex == 0){//页面显示待处理报警时，才加载数据
//				if(selectCommNO != null && !"".equals(selectCommNO)){
//					pageVo = getAlarmPendingInfo(alarmType,selectCommNO.split(","),alarmKindIds,page,pageSize);
//				}else{
//					pageVo = getAlarmPendingInfo(alarmType,commnos,alarmKindIds,page,pageSize);
//				}
//			}
//
//			result.put("list", list);
//			result.put("pendingList", JSON.toJSONString(pageVo));
//		} catch (Exception e) {
//			e.printStackTrace();
//			result.put("data", "-1");
//			logger.error(e.getMessage());
//			result.put("msg", "接口程序报错");
//		}
//		return result;
//	}
//	
	/**
	 * 查询待处理报警
	 * 
	 */
//	@ResponseBody
//	@RequestMapping(value = "/pending/Info.html", method = RequestMethod.POST)
//	public PageVo getAlarmPendingInfo(String paramsGrid) {
//		
//		Map<String, Object> param = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
//		String alarmType = (String) param.get("AlarmType");
//		List<TIntfObjAlarmT> AlarmList = new ArrayList<>();
//		List<TIntfObjAlarmT> alarmTempList = new ArrayList<>();
//		PageVo vo = new PageVo();
//
//		String CommNOs = param.get("CommNOs").toString();
//		String[] commnos = CommNOs.split(",");
//		Set<Integer> alarmKindIds = alarmKindUtil.getAlarmKind();
//		alarmTempList = monitorService.getAlarmT(alarmKindIds, commnos);
//		if (alarmType != null && !"".equals(alarmType)) {
//			for (TIntfObjAlarmT obj : alarmTempList) {
//				if (alarmType.equals(String.valueOf(obj.getAlarmType()))) {
//					AlarmList.add(obj);
//				}
//			}
//		} else {
//			AlarmList.addAll(alarmTempList);
//		}
//
//		List<AlarmPenddingInfo> list = new ArrayList<>();
//		long curr = System.currentTimeMillis();
//		AlarmPenddingInfo entity = null;
//		for (TIntfObjAlarmT obj : AlarmList) {
//			if (curr - obj.getAlarmTime() <= ALARM_BUSINESS_TIME) {
//				entity = new AlarmPenddingInfo();
//
//				entity.setAlarmTypeId(String.valueOf(obj.getAlarmType()));
//				entity.setAlarmType(staticAlarmMap.get(obj.getAlarmType()));
//				entity.setCommNo(obj.getCommNo());
//				entity.setAlarmInfo(obj.getAlmParams());
//				entity.setAlarmTime(DateUtil.getDateFromLong(obj.getAlarmTime(), " yyyy-MM-dd HH:mm:ss"));
//				entity.setTime(obj.getAlarmTime());
//				if (obj.getSourceID() == 1) {
//					entity.setAlarmSource("终端报警");
//				} else {
//					entity.setAlarmSource("平台报警");
//				}
//				list.add(entity);
//			}
//		}
//		int fromNO = Integer.parseInt(param.get("fromNumber").toString());
//		int pageSize = Integer.parseInt(param.get("pageSize").toString());
//		int page = Integer.parseInt(param.get("page").toString());
//		int limit =pageSize*page;
//		Collections.sort(list);
//		List<AlarmPenddingInfo> result = new ArrayList<>();
//		for(int j=fromNO;j<limit;j++){
//			if(j<=list.size()-1){
//				entity = list.get(j);
//				entity.setRowId(j+1);
//				result.add(entity);
//			}
//		}
//		vo.setRows(result);
//		vo.setTotal(list.size());
//		vo.setPage(page);
//
//		return vo;
//	}

	@ResponseBody
	@RequestMapping(value = "/pending/detailInfo.html", method = RequestMethod.POST)
	public HashMap<String, Object> getAlarmPendingDetailInfo(@RequestBody String postData) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("data", "-1");
		try {
			HashMap<String, Object> param = JSON.parseObject(postData, HashMap.class);
			SysUser user = getSysUser();
			Integer userId = user.getId();
			param.put("userId", userId);
			if (!param.containsKey("AlarmType")) {
				param.put("AlarmType", 2);
			}
			if (!param.containsKey("VehicleID")) {
				param.put("VehicleID", 0);
			}
			List<AlarmPenddingInfo> list = alarmService.getAlarmPendingDetailInfo(param);
			result.put("list", list);
			result.put("data", "0");
		} catch (Exception e) {
			result.put("msg", "程序报错");
			logger.error("{}", e.getMessage());
		}
		return result;
	}

	/**
	 * 实时报警处理业务逻辑 按照车辆，报警类型进行处理，步骤 1. 新增 alarm_dealinfo表的记录 2.
	 * 修改alarm_info_operation的dealer_id关联刚新增字段 3. 把该车，该报警类型的当天的业务数据全部迁移到历史表 4.
	 * 前面的步骤执行完毕后,查询该车是否有报警，如无，清楚redis该车的报警数据
	 */
	@ResponseBody
	@RequestMapping(value = "/realtime/handler.html", method = RequestMethod.POST)
	public HashMap<String, String> handler(@RequestBody String postData) {
		HashMap<String, String> result = new HashMap<String, String>();
		result.put("data", "-1");
		try {
			HashMap<String, Object> param = JSON.parseObject(postData, HashMap.class);
			if (param.get("vehicleId") == null || "".equals(param.get("vehicleId"))) {
				result.put("msg", "车辆id为空");
				return result;
			}
			if (param.get("alarmType") == null || "".equals(param.get("alarmType"))) {
				result.put("msg", "报警类型为空");
				return result;
			}
			SysUser user = getSysUser();
			Integer userId = user.getId();
			param.put("userId", userId);

			AlarmDealInfo alarmDeal = new AlarmDealInfo();
			alarmDeal.setAlarmType(Integer.parseInt(param.get("alarmType").toString()));
			alarmDeal.setVehicleId(Integer.parseInt(param.get("vehicleId").toString()));
			alarmDeal.setTransactMan(userId);
			alarmDeal.setUserName(user.getLogin_name());
			alarmDeal.setTransactResult("result");
			alarmDeal.setTransactContent("content");
			alarmDeal.setTransactResult(param.get("result").toString());
			alarmDeal.setTransactContent(param.get("content").toString());
			// 按照处理时间进行分表处理
			alarmDeal.setTable(DateUtil.getDateTimeString(new Date(), null).substring(0, 7).replace("-", "_"));
			Set<Integer> alarmKindIds=new HashSet<>();
			alarmKindIds.add(Integer.parseInt(param.get("alarmType").toString()));
			this.alarmService.saveHandler(alarmKindIds, alarmDeal);

			result.put("data", "0");
		} catch (Exception e) {
			result.put("msg", "程序报错");
			logger.error("{}", e.getMessage());
		}
		return result;
	}

	/**
	 * 历史报警处理业务逻辑 按照车辆，报警类型进行处理，步骤 1. 新增 alarm_dealinfo表的记录 2.
	 * 修改alarm_info_operation的dealer_id关联刚新增字段 3. 把该车，该报警类型的当天的业务数据全部迁移到历史表
	 *
	 * @param postData
	 *            接收前端传递的车辆id，报警id，报警时间 格式： [ {vehicle_id:vid, alarmkind_id:aid,
	 *            alarmtime:atime } ]
	 */
	@ResponseBody
	@RequestMapping(value = "/history/handler.html", method = RequestMethod.POST)
	public HashMap<String, String> handlerHis(@RequestBody String postData, HttpServletRequest request) {
		HashMap<String, String> result = new HashMap<String, String>();
		result.put("data", "-1");
		try {
			HashMap<String, Object> params = JSON.parseObject(postData, HashMap.class);

			if (params == null || params.isEmpty()) {
				result.put("msg", "参数为空");
				return result;
			}

			SysUser user = getSysUser();
			Integer userId = user.getId();
			params.put("userId", userId);
			String[] time = params.get("alarmTime").toString().split(",");
			for (int i = 0; i < time.length; i++) {
				params.replace("alarmTime", time[i]);
				AlarmDealInfo alarmDeal = new AlarmDealInfo();
				alarmDeal.setTransactMan(userId);
				alarmDeal.setUserName(user.getLogin_name());
				alarmDeal.setTransactResult(params.get("result").toString());
				alarmDeal.setTransactContent(params.get("content").toString());
				// 按照处理时间进行分表处理
				alarmDeal.setTable(DateUtil.getDateTimeString(new Date(), null).substring(0, 7).replace("-", "_"));

				this.alarmService.saveHisHander(alarmDeal, params);
			}
			result.put("data", "0");
		} catch (Exception e) {
			result.put("msg", "程序报错");
			logger.error("{}", e.getMessage());
		}
		return result;
	}

	/**
	 * 查询当天报警分时段统计信息
	 */
	@ResponseBody
	@RequestMapping(value = "/realtime/hourGroup.html", method = RequestMethod.GET)
	public PageVo getAlarmByHourGroupStatistics(String AlarmType, HttpServletRequest request) {
		try {
			SysUser user = getSysUser();
			Integer userId = user.getId();
			Map<String, Object> param = new HashMap<String, Object>();
			if (AlarmType == null || AlarmType == "") {
				logger.info(" user {} query alarm realtime hourGroup statistics", "AlarmType不能為空");
				return new PageVo();
			}
			param.put("AlarmType", AlarmType);
			param.put("userId", userId);
			param.put("todayTime", new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
			param.put("table", param.get("todayTime").toString().substring(0, 7).replace("-", "_"));

			logger.debug(" user {} query alarm realtime hourGroup statistics", param);
			List<AlarmHourStatistics> list = alarmService.getAlarmByHourGroupStatistics(param);
			PageVo pageVo = new PageVo();
			pageVo.setRows(list);
			pageVo.setTotal(list.size());
			return pageVo;
		} catch (Exception e) {
			logger.error(" user {} query alarm realtime hourGroup statistics", e);
			return new PageVo();
		}
	}

	/**
	 * 查询当天报警分时段统计报警的明细数据 说明:传入报警类型,和时间段,查询该类型下所有车辆的最后一次报警数据
	 */
	@ResponseBody
	@RequestMapping(value = "/realtime/hourDetail.html", method = RequestMethod.GET)
	public PageVo hourDetail(String paramsGrid, HttpServletRequest request) {
		try {
			SysUser user = getSysUser();
			Map<String, Object> param = new HashMap<String, Object>();
			if (paramsGrid != null) {
				param = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			}
			Integer userId = user.getId();
			param.put("userId", userId);
			Date date = new Date();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String time = format.format(date);
			String StartTime = time + " " + (String) param.get("startTime");
			String EndTime = time + " " + (String) param.get("endTime");
			param.put("startTime", StartTime);
			param.put("endTime", EndTime);
			// 日期分表
			param.put("table", param.get("startTime").toString().substring(0, 7).replace("-", "_"));

			int page = (int) param.get("page");
			int pageSize = (int) param.get("pageSize");
			param.put("startRow", (page - 1) * pageSize);
			param.put("limit", pageSize);
			logger.debug(" user {} query alarm realtime hourDetail statistics", param);
			List<AlarmPenddingInfo> alarmPenddingInfoList = new ArrayList<AlarmPenddingInfo>();
			
			PageVo pageVo = new PageVo();
			if(param.get("alarmType") != null && !"".equals(param.get("alarmType"))){
				alarmPenddingInfoList = this.alarmService.getAlarmByHourDetailStatistics((HashMap<String, Object>) param);
				pageVo.setTotal(this.alarmService.getAlarmByHourDetailStatisticsCount((HashMap<String, Object>) param));
			}else{
				pageVo.setTotal(0);
			}
			pageVo.setRows(alarmPenddingInfoList);
			pageVo.setPage((int) param.get("page"));
			return pageVo;
		} catch (Exception e) {
			logger.error(" user {} query alarm realtime hourDetail statistics", e.getMessage());
			return new PageVo();
		}
	}

	/**
	 * 查询历史报警明细数据 说明:传入车牌号，报警类型,报警时间，时间段,查询该类型下所有车辆的最后一次报警数据 历史报警分表查询逻辑 1.
	 * 如果查询日期隔月,分两次查询 前端展示按照时间倒序，因此后面的日期先查询,如果条数不满分页数据，则进行第二次查询 2. 总数必须查询两次,进行汇总
	 */
	@ResponseBody
	@RequestMapping(value = "/history/list.html", method = RequestMethod.POST)
	public PageVo hisList(String paramsGrid, HttpServletRequest request) {
		SysUser user = getSysUser();

		Map<String, Object> param = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		param.put("userId", user.getId());

		PageVo pageVo = alarmService.getHistoryAlarm(param);

		return pageVo;
	}

	/**
	 * 测试导出excel表格
	 */
	@RequestMapping(value = "exportInfo.html")
	public void exportInfo(HttpServletResponse response, HttpServletRequest request, String paramsGrid, String colModel,
			String title, Integer startPage, Integer endPage, String imgsrc) {
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		List<String> imgsrcList = JSON.parseObject(imgsrc, List.class);
		ParamMap param = FlexiGridUtil.parseJSONParam(paramsGrid);
		Map<String, Object> paramMap = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		// paramMap.put("_vin_list", "");
		// 返回公共的参数
		// paramMap.putAll(getHashMapParamMap(request,paramMap,"export"));
		// 没分页查询
		Object fromRow = String.valueOf(paramMap.get("_start_row")); // 开始行
		Object toRow = String.valueOf(paramMap.get("_end_row")); // 结束行
		paramMap.put("fromNumber", "0"); // 开始行
		paramMap.put("pageSize", "10");
		SysUser user = this.getSysUser();
		Integer userId = user.getId();
		paramMap.put("userId", userId);
		if (!paramMap.containsKey("AlarmType")) {
			paramMap.put("AlarmType", 0);
		}
		if (!paramMap.containsKey("VehicleID")) {
			paramMap.put("VehicleID", 0);
		}

		PageVo pageVo = alarmService.getAlarmPendingInfo(paramMap);
		List<AlarmPenddingInfo> result = (List<AlarmPenddingInfo>) pageVo.getRows();
		List<HashMap<String, String>> rows = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = null;
		for (AlarmPenddingInfo alarm : result) {
			map = new HashMap<String, String>();
			map.put("registrationNO", alarm.getRegistrationNO());
			map.put("internalNumber", alarm.getInternalNumber());
			map.put("vehicleTeamName", alarm.getVehicleTeamName());
			map.put("alarmType", alarm.getAlarmType());
			map.put("alarmInfo", alarm.getAlarmInfo());
			map.put("alarmTime", alarm.getAlarmTime());

			rows.add(map);
		}
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		int index = -1;
		/*
		 * if(colModelList.toString().indexOf("操作")!=-1){ index=0; }
		 */
		exportExl(request, response, title, removeHeadName(colModelList, index, -1), rowsList, imgsrcList);
	}

	@RequestMapping(value = "queryAlarm.html")
	@ResponseBody
	public Map<String, Object> queryUserVehicle(HttpServletRequest req, HttpServletResponse res, Model model) {
		HashMap<String, Object> param = getReqParameters();
		List alarmList = alarmService.queryAlarmByCondition(param);
		Map<String, Object> map = new HashMap<>();
		map.put("vehicleList", alarmList);
		return map;
	}

	/**
	 * 查询该用户下的车辆是否存在实时报警
	 */
//	@ResponseBody
//	@RequestMapping(value = "/hasAlarm.html", method = RequestMethod.GET)
//	public HashMap<String, String> hasAlarm() {
//		HashMap<String, String> result = new HashMap<String, String>();
//		result.put("data", "-1");
//		try {
//			SysUser user = this.getSysUser();
//			HashMap<String, Object> param = new HashMap<String, Object>();
//			param.put("userId", user.getId());
//			
//			List<HashMap<String, String>> vehList = this.alarmService.getVehStaticInfo(param);
//			List<String> list = new ArrayList<String>();
//			HashMap<String, String> item = null;
//			for(int i = 0;i < vehList.size();i++){
//				item = vehList.get(i);
//				if(item != null && item.get("CommNO") != null ){
//					list.add(item.get("CommNO"));
//				}
//			}
//			String[] comms = new String[list.size()];
//			List<TIntfObjAlarm> alarmList = monitorService.getAlarm(list.toArray(comms));
//			if (alarmList != null && !alarmList.isEmpty()) {
//				result.put("data", "0");
//				String state = "0";
//				Object voice = request.getSession().getAttribute(Constant.ALARM_VOICE_STATE);
//				if (voice != null) {
//					state = voice.toString();
//				}
//				result.put("voice", state);
//			}
//		} catch (Exception e) {
//			logger.error("{}", e.getMessage());
//		}
//		return result;
//	}

	/**
	 * 历史报警轨迹定位
	 */
	@RequestMapping(value = "/history/location.html", method = RequestMethod.GET)
	public ModelAndView historyLocation(Integer vehicleID, String alarmType, String alarmTime, String lon, String lat,
			Integer gpsSpeed, Integer head) {
		ModelAndView modelAndView = new ModelAndView();
		/**
		 * 1. 查询车牌号 2. 查询报警定位数据 3.
		 */
		String registrationNO = this.alarmService.getVehicleInfo(vehicleID);
		modelAndView.addObject("registrationNO", registrationNO);
		modelAndView.addObject("lon", lon);
		modelAndView.addObject("lat", lat);
		modelAndView.addObject("alarmType", alarmType);
		modelAndView.addObject("alarmTime", alarmTime);
		modelAndView.addObject("gpsSpeed", gpsSpeed);
		modelAndView.addObject("head", head);
		modelAndView.setViewName("views/business/alarm/alarmLocation");
		return modelAndView;
	}

	/**
	 * 设置报警声音开关状态
	 * 
	 * @param postData
	 *            {"state":1},0 开启，1关闭
	 */
	@ResponseBody
	@RequestMapping(value = "/setVoice.html", method = RequestMethod.POST)
	public HashMap<String, String> setVoice(@RequestBody String postData) {
		HashMap<String, String> result = new HashMap<String, String>();
		try {
			HashMap<String, String> param = JSON.parseObject(postData, HashMap.class);
			this.request.getSession().setAttribute(Constant.ALARM_VOICE_STATE, param.get("state"));
			result.put("data", "0");
		} catch (Exception e) {
			logger.error("{}", e.getMessage());
			result.put("data", "-1");
		}
		return result;
	}
	
	
	/**
	 * 加载报警名称
	 */
	static {
		staticAlarmMap.put(1, "紧急报警");
		staticAlarmMap.put(2, "超速报警");
		staticAlarmMap.put(3, "疲劳驾驶");
		staticAlarmMap.put(4, "预警");
		staticAlarmMap.put(5, "GNSS模块发生故障");
		staticAlarmMap.put(6, "GNSS天线未接或被剪断");
		staticAlarmMap.put(7, "GNSS天线短路");
		staticAlarmMap.put(8, "终端主电源欠压");
		staticAlarmMap.put(9, "终端主电源掉电");
		staticAlarmMap.put(10, "终端LCD或显示器故障");
		staticAlarmMap.put(11, "TTS模块故障 ");
		staticAlarmMap.put(12, "摄像头故障 ");
		staticAlarmMap.put(13, "当天累计驾驶超时");
		staticAlarmMap.put(14, "超时停车");
		staticAlarmMap.put(15, "进出区域");
		staticAlarmMap.put(16, "进出路线");
		staticAlarmMap.put(17, "路段行驶时间不足/过长");
		staticAlarmMap.put(18, "路线偏离报警");
		staticAlarmMap.put(19, "车辆VSS故障");
		staticAlarmMap.put(20, "车辆油量异常");
		staticAlarmMap.put(21, "车辆被盗");
		staticAlarmMap.put(22, "车辆非法点火");
		staticAlarmMap.put(23, "车辆非法位移");
		staticAlarmMap.put(24, "碰撞侧翻报警");
		staticAlarmMap.put(25, "SD卡异常");
		staticAlarmMap.put(26, "进入区域");
		staticAlarmMap.put(27, "离开区域");
		staticAlarmMap.put(34, "迟到报警");
		staticAlarmMap.put(35, "禁止报警");
		staticAlarmMap.put(36, "超速报警");
		staticAlarmMap.put(37, "低速报警");
		staticAlarmMap.put(38, "超时报警");
		staticAlarmMap.put(39, "提前报警");
		staticAlarmMap.put(40, "规定速度超时报警");
		staticAlarmMap.put(41, "规定速度提前报警");
		staticAlarmMap.put(43, "非法开门");
		staticAlarmMap.put(46, "驾驶员吸烟报警");
		staticAlarmMap.put(47, "驾驶员姿态异常报警");
		staticAlarmMap.put(48, "疲劳驾驶报警");
		staticAlarmMap.put(49, "前车防碰撞预警");
		staticAlarmMap.put(50, "驾驶员打电话报警");
		staticAlarmMap.put(51, "车道偏离报警");
		staticAlarmMap.put(52, "车辆超时报警");
		staticAlarmMap.put(53, "振动报警");
		staticAlarmMap.put(54, "GPRS报警");
		staticAlarmMap.put(55, "进入道路报警");
		staticAlarmMap.put(56, "出道路报警");
		staticAlarmMap.put(57, "道路超速报警");
		staticAlarmMap.put(58, "区域内超速报警");
		staticAlarmMap.put(59, "规定时间内进入路段报警");
		staticAlarmMap.put(60, "盲区报警");
		staticAlarmMap.put(61, "手柄故障");
		staticAlarmMap.put(100, "聚集报警");
		staticAlarmMap.put(301, "紧急报警");
		staticAlarmMap.put(302, "超速报警");
		staticAlarmMap.put(303, "疲劳驾驶报警");
		staticAlarmMap.put(304, "越界报警");
		staticAlarmMap.put(305, "偏离路线报警");
		staticAlarmMap.put(306, "车辆移动报警");
		staticAlarmMap.put(307, "超时驾驶报警");
		staticAlarmMap.put(308, "进入指定区域报警");
		staticAlarmMap.put(309, "离开指定区域报警");
		staticAlarmMap.put(310, "路段堵塞报警");
		staticAlarmMap.put(311, "危险路段报警");
		staticAlarmMap.put(312, "盗警");
		staticAlarmMap.put(313, "劫警");
		staticAlarmMap.put(314, "其他报警");
		staticAlarmMap.put(315, "超速报警");
		staticAlarmMap.put(316, "疲劳驾驶报警");
		staticAlarmMap.put(317, "地点超时停车报警");
		staticAlarmMap.put(318, "进出地点报警");
		staticAlarmMap.put(319, "进出区域报警");
		staticAlarmMap.put(320, "路段偏离报警");
		staticAlarmMap.put(321, "夜间行车报警");
		staticAlarmMap.put(322, "分路段超速报警");
		staticAlarmMap.put(323, "进入指定区域报警");
		staticAlarmMap.put(324, "离开指定区域报警");
		staticAlarmMap.put(325, "规定时间未到达指定地点报警");
		staticAlarmMap.put(326, "规定时间未离开指定地点报警");
		staticAlarmMap.put(9999, "离线报警");
		staticAlarmMap.put(100101, "摄像头遮挡报警");
		staticAlarmMap.put(100102, "超时停车报警");
		staticAlarmMap.put(100103, "非法停车报警");
		staticAlarmMap.put(100104, "GPS盲区报警");
		staticAlarmMap.put(100105, "摄像头无信号报警");
		staticAlarmMap.put(100106, "视频断电报警");
		staticAlarmMap.put(100107, "GPS断电报警");
		staticAlarmMap.put(100197, "疲劳驾驶报警");
		staticAlarmMap.put(100198, "终端线路偏移报警");
		staticAlarmMap.put(100199, "进入矩形区域报警");
		staticAlarmMap.put(100201, "离开矩形区域报警");
		staticAlarmMap.put(100202, "进入圆形区域报警");
		staticAlarmMap.put(100203, "离开圆形区域报警");
		staticAlarmMap.put(100204, "规定时间未到达指定地点报警");
		staticAlarmMap.put(100205, "规定时间未离开指定地点报警");
		staticAlarmMap.put(100206, "路段超速报警");
		staticAlarmMap.put(100300, "疲劳驾驶报警");
		staticAlarmMap.put(100301, "车辆行驶段落");
		staticAlarmMap.put(100302, "限制时间");
		staticAlarmMap.put(100303, "超时停车");
		staticAlarmMap.put(100304, "刹车统计");
		staticAlarmMap.put(100305, "空调工作");
		staticAlarmMap.put(100306, "发动机开统计");
		staticAlarmMap.put(100307, "启动报警");
		staticAlarmMap.put(100308, "温度报警");
		staticAlarmMap.put(100309, "驾驶员身份验证");
		staticAlarmMap.put(100310, "开厢报警");
		staticAlarmMap.put(100311, "拯救车队报警");
		staticAlarmMap.put(100312, "异常Gps");
		staticAlarmMap.put(100313, "超速报警");
		staticAlarmMap.put(100314, "停车引擎报警");
		staticAlarmMap.put(100315, "路桥费用");
		staticAlarmMap.put(100316, "路段超时停车");
		staticAlarmMap.put(100317, "运行报表");
		staticAlarmMap.put(100318, "路段超速");
		staticAlarmMap.put(100319, "道路偏离");
		staticAlarmMap.put(100320, "道路类型超速");
		staticAlarmMap.put(100321, "里程统计");
		staticAlarmMap.put(100322, "每日里程记录");
		staticAlarmMap.put(100323, "每时里程记录");
		staticAlarmMap.put(100324, "区域进出检测");
		staticAlarmMap.put(100325, "站点进出时间");
		staticAlarmMap.put(100326, "站点进出次数");
		staticAlarmMap.put(100327, "进出站停车次数报警");
		staticAlarmMap.put(100328, "站点进出提示");
		staticAlarmMap.put(100329, "站点报表");
		staticAlarmMap.put(100330, "业务跟踪");
		staticAlarmMap.put(100331, "混凝土工作内容");
		staticAlarmMap.put(100332, "混凝土工作流程");
		staticAlarmMap.put(100333, "开车搅拌罐停止转动超时报警");
		staticAlarmMap.put(100334, "状态变动");
		staticAlarmMap.put(100335, "搅拌罐变换转动方向分析");
		staticAlarmMap.put(100336, "指定时间段区域报警");
		staticAlarmMap.put(100337, "油位报警");
		staticAlarmMap.put(100338, "温度增量报警");
		staticAlarmMap.put(100339, "油位增量报警");
		staticAlarmMap.put(100340, "休息区报警");
		staticAlarmMap.put(100341, "弯道超速");
		staticAlarmMap.put(100342, "按时长超速报警");
		staticAlarmMap.put(100343, "凯运-按时长超速报警");
		staticAlarmMap.put(100344, "道路类型行驶");
		staticAlarmMap.put(100345, "冷柜监控报警");
		staticAlarmMap.put(100346, "道路类型超速(长运)");
		staticAlarmMap.put(100347, "超速行驶报警");
		staticAlarmMap.put(100348, "摄像头关");
		staticAlarmMap.put(100349, "司机疲劳驾驶报警");
		staticAlarmMap.put(100350, "路桥费用");
		staticAlarmMap.put(100351, "司机超速行驶报警");
		staticAlarmMap.put(100352, "道路行驶速度分析");
		staticAlarmMap.put(100353, "里程保养分析");
		staticAlarmMap.put(100354, "行驶速度分析");
		staticAlarmMap.put(100355, "每月里程记录");
		staticAlarmMap.put(100356, "行驶速度分析(交委)");
		staticAlarmMap.put(100357, "ACC状态检测报警");
		staticAlarmMap.put(100358, "疲劳驾驶报警(交委)");
		staticAlarmMap.put(100359, "区域弯道超速");
		staticAlarmMap.put(100360, "凯运-生活区报警");
		staticAlarmMap.put(100361, "凯运-超时停车");
		staticAlarmMap.put(100362, "广汽日野车辆停运检测");
		staticAlarmMap.put(100363, "广汽日野车终端盲区检测");
		staticAlarmMap.put(100364, "车辆聚集报警");
		staticAlarmMap.put(100365, "区域超时停留");
		staticAlarmMap.put(100366, "道路进出监控");
		staticAlarmMap.put(100367, "道路停留超时");
		staticAlarmMap.put(100368, "区域进出监控");
		staticAlarmMap.put(100369, "进出电子围栏(视频)");
		staticAlarmMap.put(100370, "区域停车超时报警");
		staticAlarmMap.put(100371, "收发车记录");
		staticAlarmMap.put(100372, "车辆行车报警");
		staticAlarmMap.put(100373, "转向灯检测");
		staticAlarmMap.put(100374, "发动机开检测");
		staticAlarmMap.put(100375, "指定线路报警");
		staticAlarmMap.put(100376, "超载报警");
		staticAlarmMap.put(100377, "高速限时营运报警");
		staticAlarmMap.put(100501, "超速预警");
		staticAlarmMap.put(100502, "超速高速报警");
		staticAlarmMap.put(100503, "超速低速报警");
		staticAlarmMap.put(100504, "疲劳驾驶预警");
		staticAlarmMap.put(100505, "地点范围内停车超时报警");
		staticAlarmMap.put(100506, "地点范围外停车超时报警");
		staticAlarmMap.put(100507, "进入指定地点报警");
		staticAlarmMap.put(100508, "离开指定地点报警");
		staticAlarmMap.put(100509, "低速预警");
		staticAlarmMap.put(100510, "低温报警");
		staticAlarmMap.put(100511, "高温报警");
		staticAlarmMap.put(100512, "温度变化报警");
		staticAlarmMap.put(100513, "油量骤增报警");
		staticAlarmMap.put(100514, "油量骤减报警");
		staticAlarmMap.put(100515, "油量消耗报警");
		staticAlarmMap.put(100516, "转鼓停转报警");
		staticAlarmMap.put(100519, "路段超速报警");
		staticAlarmMap.put(100520, "空调超时使用");
	}
	
	/*
     * 统计异常
     * 获取报警类型
     */
    @ResponseBody
    @RequestMapping(value="getAlarmKind.html",method = RequestMethod.GET)  
    public List<HashMap<String, Object>> getAlarmKind(HttpServletRequest req,HttpServletResponse res){
    	Set<Integer> alarmKindIds = alarmKindUtil.staticAnormalStr();
    	Map<String, Object> params = new HashMap<>();
    	String name = req.getParameter("name");
    //	params.put("selected", "selected");
    	params.put("name", name);
    	params.put("alarmKindIds", alarmKindIds);
    	return alarmService.queryAlarmType(params);
    }
}
